with sharing public class OverrideSubRegionMonthlyBudget
{
    public String msg{get;set;}
    public String msg1{get;set;}
    public String IdSelect{get;set;}
    public Boolean DisplayApprove{get;set;}
    public Boolean DisplaySubmit{get;set;}
    public Boolean DisplaySave{get;set;}
    public Boolean ForUpdate;
    Integer Inequality = 0;

     public RegionalBudget__c RegionalBudget{
         get{
             if(RegionalBudget== null)
                 RegionalBudget= new RegionalBudget__c();
             return RegionalBudget;
         }
         set;
    }

    
    public Sub_Region_Budget__c SubRegionBudget{
         get{
             if(SubRegionBudget== null)
                 SubRegionBudget= new Sub_Region_Budget__c();
             return SubRegionBudget;
         }
         set;
    }  
    public Sub_regional_Monthly_Budget__c SubRegionMonthlyBudget{
         get{
             if(SubRegionMonthlyBudget== null)
                 SubRegionMonthlyBudget= new Sub_regional_Monthly_Budget__c();
             return SubRegionMonthlyBudget;
         }
         set;
    }          
    
    public PE_Sample_Management__c PESM {
         get{
             if(PESM == null)
                 PESM = new PE_Sample_Management__c();
             return PESM ;
         }
         set;
    }      
        
    public List<TableItemControl> TableItemsDown{         
        get{
             if(TableItemsDown== null)
                 TableItemsDown= new List<TableItemControl>();
             return TableItemsDown;
         }
        set;
    }    
    
    public String UrlId
    {
        get{        
            return System.currentPageReference().getParameters().get('id');     
        }  
        set;
    }
    public String RegionalId
    {
        get{        
            return System.currentPageReference().getParameters().get('Rid');     
        }  
        set;
    }     
    public List<Sub_Region_Budget__c> ExistRecord = new List<Sub_Region_Budget__c>();
    public Sub_Region_Budget__c SelectedRecord{
        get{        
             if(SelectedRecord== null)
                 SelectedRecord= new Sub_Region_Budget__c();
             return SelectedRecord;
        }  
        set;
    }
    public List<Place__c> pList = new  List<Place__c>();  
    User cu  = [Select Name,UserRoleId,Title__c From User Where Id =:UserInfo.getUserId()];
    UserRole ur = [Select Id,Name From UserRole Where Id =: cu.UserRoleId];
    
    UserRole RoleWOCRGM = [Select Id,Name From UserRole Where Name =: GlobalProperties.RoleWOCRGM ];
    UserRole RoleSOCRGM = [Select Id,Name From UserRole Where Name =: GlobalProperties.RoleSOCRGM ];
    UserRole RoleNOCRGM = [Select Id,Name From UserRole Where Name =: GlobalProperties.RoleNOCRGM ];
    UserRole RoleEOCRGM = [Select Id,Name From UserRole Where Name =: GlobalProperties.RoleEOCRGM ];
    
                     
    public List<SelectOption> options{
        get{
             if(options == null)
                options = new List<SelectOption>();
            else
                options.clear();
            // get the place from user role
            if((ur.Name == 'MMKT:EOC-Senior Regional MMKT Mgr')||(ur.Name == 'EOC Regional General Manager'))
            {
                pList = [Select id,name,Region__r.name From Place__c Where PlaceType__c = 'Sub-region' and  Region__r.Name =: '华东区'];
                
            }
            if((ur.Name == 'MMKT:NOC-Senior Regional MMKT Mgr')||(ur.Name == 'NOC Regional General Manager'))
            {     
                pList = [Select id,name,Region__r.name From Place__c Where PlaceType__c = 'Sub-region' and  Region__r.Name =: '华北区'];
            }        
            if((ur.Name == 'MMKT:SOC-Senior Regional MMKT Mgr')||(ur.Name == 'SOC Regional General Manager'))
            {    
                pList = [Select id,name,Region__r.name From Place__c Where PlaceType__c = 'Sub-region' and  Region__r.Name =: '华南区'];
            }
            if((ur.Name == 'MMKT:WOC-Senior Regional MMKT Mgr')||(ur.Name == 'WOC Regional General Manager'))
            {   
                pList = [Select id,name,Region__r.name From Place__c Where PlaceType__c = 'Sub-region' and  Region__r.Name =: '华西区'];
            }
            options.add(new SelectOption('1',' '));
            for(Place__c p : pList){
                options.add(new SelectOption(p.Name,p.Name));
            }                              
            return  options;             
        }
        set;
    } 
    public PageReference actionSupport()
    {
        msg1 = null;
        msg  = null;
        if(((ur.Name == 'WOC Regional General Manager')||(ur.Name == 'SOC Regional General Manager')||
        (ur.Name == 'NOC Regional General Manager')||(ur.Name == 'EOC Regional General Manager'))&&(DisplaySave == false))
        {
            return null;
        }
        
        if(ExistRecord.size() > 0 ){
            TableItemsDown.clear(); // clear the table item

            List<AggregateResult> TotalLastYearInMarketSales = [Select sum(InMarketSaleskg__c)InMarketSales, Month__c Mon From 
               InMarketSales__c Where InMarketSaleskg__c > 0 and Year__c =: Integer.valueof(PESM.Year__c)-1  and SubRegion__c =: IdSelect group by Month__c]; 

            List<AggregateResult> TotalThisYearInMarketSales = [Select sum(InMarketSalesForcast__c)InMarketSales, Month__c Mon From 
               InMarketSales__c Where InMarketSalesForcast__c > 0 and Year__c =: Integer.valueof(PESM.Year__c) and SubRegion__c =: IdSelect group by Month__c];                 

            List<AggregateResult> TotalLastYearPEShipment = [Select sum(KG__c)kg,Month__c Mon From Shipment__c Where KG__c > 0 and   Year__c =: Integer.valueof(PESM.Year__c)-1 and SubRegion__c =: IdSelect and CalcInKg__c =: true group by Month__c];

            List<AggregateResult> SubRegionLastYearPEConversion = [Select sum(PE_conversion_achieve__c)TotalIn,Month__c Mon  From 
                                          Achieve__c Where PE_conversion_achieve__c > 0 and   Year__c =: string.valueof(Integer.valueof(PESM.Year__c)-1) and subregion__c =: IdSelect group by Month__c];
            
            List<AggregateResult> SubRegionThisYearPEConversion = [Select sum(PE_Conversion_forecast__c)TotalIn,Month__c Mon  From 
                                          Achieve__c Where PE_Conversion_forecast__c > 0 and   Year__c =: PESM.Year__c and subregion__c =: IdSelect group by Month__c];

            Decimal TotalLastYearPEShipmentValue = 0;

            Decimal TotalLastYearPEConversionValue = 0;
            Decimal TotalThisYearPEConversionValue = 0;
            Decimal TotalLastYearInMarketSalesValue = 0;
            Decimal TotalThisYearInMarketSalesValue = 0;
                                     
            for(Integer i = 1; i < 13;i++) // put 12 monthes to table
            {
                TableItemControl T = new TableItemControl();
                T.Str = String.valueof(i);
                Decimal LastYearPEShipmentValue = 0;

                Decimal SubRegionLastYearInMarketSalesValue = 0;
                Decimal SubRegionThisYearInMarketSalesValue = 0;                
                Decimal LastYearPEConversionValue = 0;
                Decimal ThisYearPEConversionValue = 0;
                for(AggregateResult ag : TotalLastYearInMarketSales)
                {
                    if(Integer.valueof(ag.get('Mon'))== i)
                    {
                        SubRegionLastYearInMarketSalesValue = (Decimal)ag.get('InMarketSales');
                    }
                }                
                for(AggregateResult ag : TotalThisYearInMarketSales)
                {
                    if(Integer.valueof(ag.get('Mon'))== i)
                    {
                        SubRegionThisYearInMarketSalesValue = (Decimal)ag.get('InMarketSales');
                    }
                }  
                for(AggregateResult ag : TotalLastYearPEShipment)
                {
                    if(Integer.valueof(ag.get('Mon'))== i)
                    {
                        LastYearPEShipmentValue = (Decimal)ag.get('kg');
                    }
                }   
             
                for(AggregateResult ag : SubRegionLastYearPEConversion)
                {
                    if(Integer.valueof(ag.get('Mon'))== i)
                    {
                        LastYearPEConversionValue = (Decimal)ag.get('TotalIn');
                    }
                }                                                  
                for(AggregateResult ag : SubRegionThisYearPEConversion)
                {
                    if(Integer.valueof(ag.get('Mon'))== i)
                    {
                        ThisYearPEConversionValue = (Decimal)ag.get('TotalIn');
                    }
                }

                TotalLastYearPEShipmentValue += LastYearPEShipmentValue;
                TotalLastYearPEConversionValue += LastYearPEConversionValue;
                TotalThisYearPEConversionValue += ThisYearPEConversionValue;
                TotalLastYearInMarketSalesValue += SubRegionLastYearInMarketSalesValue;
                TotalThisYearInMarketSalesValue += SubRegionThisYearInMarketSalesValue;
                
                
                T.SRMB.This_year_In_market_sales_kg__c = 0;
                T.SRMB.This_year_PE_Sample_kg__c = 0;
                T.SRMB.ConversionForcast__c = ThisYearPEConversionValue;
                T.SRMB.InMarketValueHide__c = SubRegionThisYearInMarketSalesValue;
                
                if(LastYearPEShipmentValue > 0)
                    T.SRMB.Last_year_In_market_sales_kg__c= SubRegionLastYearInMarketSalesValue / LastYearPEShipmentValue;
                else
                    T.SRMB.Last_year_In_market_sales_kg__c = 0;
                if(LastYearPEConversionValue > 0)   
                    T.SRMB.Last_year_PE_Sample_kg__c = LastYearPEShipmentValue / LastYearPEConversionValue;
                else
                    T.SRMB.Last_year_PE_Sample_kg__c = 0;       
                TableItemsDown.add(T);
                
            }
                TableItemControl TT = new TableItemControl();
                TT.Str = '总计';
                if(TotalLastYearPEShipmentValue > 0) 
                    TT.SRMB.Last_year_In_market_sales_kg__c = TotalLastYearInMarketSalesValue / TotalLastYearPEShipmentValue ;
                else
                    TT.SRMB.Last_year_In_market_sales_kg__c = 0;
                if(TotalLastYearPEConversionValue > 0) 
                    TT.SRMB.Last_year_PE_Sample_kg__c = TotalLastYearPEShipmentValue / TotalLastYearPEConversionValue ;
                else
                    TT.SRMB.Last_year_PE_Sample_kg__c = 0;               

                TT.SRMB.This_year_In_market_sales_kg__c = 0;
                TT.SRMB.This_year_PE_Sample_kg__c = 0;
                TT.SRMB.ConversionForcast__c = TotalThisYearPEConversionValue;
                TT.SRMB.InMarketValueHide__c = TotalThisYearInMarketSalesValue;
                
                TableItemsDown.add(TT);
            // new amount item
            
            List<Sub_Region_Budget__c> SelectedRecordList = [Select s.Year__c,s.InMarketValueHide__c,s.ConversionForcast__c, s.Rate__c, s.Total_budget_kg__c, s.Total_budget_RMB__c, s.Id,total_score__c,
                s.final_weighting__c,s.Changed__c  From Sub_Region_Budget__c s Where s.name =: PESM.Year__c +'年'+ IdSelect + '专业样品管理' and s.PE_Sample_Management__c =: PESM.Id];  
           
           if(SelectedRecordList.size() > 0){
               // get selected sub-regjion budget record info
                ForUpdate = false;
                SelectedRecord = SelectedRecordList[0];
                SubRegionMonthlyBudget.Budget_KG__c = SelectedRecord.Total_Budget_KG__c;
                SubRegionMonthlyBudget.Budget_RMB__c = SelectedRecord.Total_budget_RMB__c;
                
                List<Sub_regional_Monthly_Budget__c> existMonBud = [Select s.Year__c,s.InMarketValueHide__c,s.ConversionForcast__c, s.This_year_PE_Sample_kg__c, s.This_year_In_market_sales_kg__c,
                  s.Sub_Region_Budget__c,  s.Last_year_PE_Sample_kg__c,s.Month__c, s.Last_year_In_market_sales_kg__c,  s.Budget_RMB__c,s.Budget_KG__c 
                  From Sub_regional_Monthly_Budget__c s Where s.Sub_Region_Budget__c =: SelectedRecord.id];
                if(existMonBud.size() > 0){
                    // set exist records to table items
                    for(Sub_regional_Monthly_Budget__c sr : existMonBud)
                    {
                        for(TableItemControl t1 : TableItemsDown)
                        {
                            if(sr.Month__c == t1.str)
                            {
                                t1.SRMB = sr;
                                ForUpdate = true; 
                            }
                        }
                    }
                }
            }     
         }          
        
        return null;

    } 
    public OverrideSubRegionMonthlyBudget(){
        // set flags    
        msg1 = null;
        DisplaySubmit = false;
        DisplayApprove = false;
        DisplaySave = true;


        PESM = [Select id,Year__c,Rate__c,Deal__c,EOC_budget_allocation_kg__c,EOC_Total_budget_RMB__c,SOC_budget_allocation_kg__c,SOC_Total_budget_RMB__c  
                ,NOC_budget_allocation_kg__c,NOC_Total_budget_RMB__c,WOC_budget_allocation_kg__c,WOC_Total_budget_RMB__c 
                From PE_Sample_Management__c Where id =: UrlId];
        


        if((ur.Name == 'MMKT:EOC-Senior Regional MMKT Mgr')||(ur.Name == 'MMKT:NOC-Senior Regional MMKT Mgr')
            ||(ur.Name == 'MMKT:SOC-Senior Regional MMKT Mgr')||(ur.Name == 'MMKT:WOC-Senior Regional MMKT Mgr'))
        {
            DisplaySubmit = true;
            DisplayApprove = false;
        }
        if((ur.Name == 'EOC Regional General Manager')|| (ur.Name == 'NOC Regional General Manager') || 
            (ur.Name == 'SOC Regional General Manager') ||(ur.Name == 'WOC Regional General Manager'))
        {
            DisplaySubmit = false;
            DisplayApprove = true; 
            ForUpdate = true;       
        }
        
        RegionalBudget = [Select r.TotalBudgetRMB__c, r.ThisYearKg_No__c, r.ThisYearKg_Kg__c, r.Submit__c, r.Region__c,
                 r.PESampleManagement__c, r.OwnerId, r.Over__c, r.Name, r.LastYearSalesWeighting__c, r.LastYearKg_No__c,
                 r.LastYearKg_Kg__c, r.LastYearConversionWeighting__c, r.Id,r.BudgetAllocationKg__c,  
                 r.Approved__c, r.ApprovalStatus__c From RegionalBudget__c r where r.id =: RegionalId];   
                                  
       if(!PESM.Deal__c)
       {
           msg = '样品管理未下发！';
           DisplaySubmit = false;
           DisplayApprove = false;
           DisplaySave = false;
       }
       else
       {  
            ExistRecord = [Select s.total_score__c, s.potential_score__c, s.final_weighting__c, s.Year__c, s.Total_budget_kg__c,
                s.Total_budget_RMB__c, s.This_year_PE_Sample_kg__c, s.This_year_In_market_sales_kg__c,  s.Submit__c, s.Sub_Region__c, s.Sales_City__c, s.Region__c, 
                s.Rate__c, s.Place__c, s.PE_Sample_Management__c, s.OwnerId, s.Name, s.Line_Manager__c, s.Last_year_sales_weighting__c,
                s.Last_year_conversion_weighting__c, s.Last_year_PE_Sample_kg__c, s.Last_year_In_market_sales_kg__c, s.IsDeleted, s.Id, s.Area__c, s.Approved__c,s.Changed__c 
                ,s.RegionalBudget__c From Sub_Region_Budget__c s Where s.RegionalBudget__c =: RegionalId];
            if(ExistRecord.size()<= 0) // sub-region budget is not ready, so can't allocate the monthly budget
            {
                msg = '您还未对片区样品进行未分配！';
                DisplaySubmit = false;
                DisplayApprove = false;
                DisplaySave = false;              
            }
            else{
               if(RegionalBudget.Approved__c == true)
               {
                    msg = '审批通过，不能再修改！';
                    DisplaySave = false;
                    DisplaySubmit = false;
                    DisplayApprove = false;                    
               } 
            
                // sub-region budget is submitted, so can't change.
               
               if((ExistRecord.size() > 0)&&((ur.Name == 'MMKT:WOC-Senior Regional MMKT Mgr')|| (ur.Name == 'MMKT:SOC-Senior Regional MMKT Mgr') 
                   ||(ur.Name == 'MMKT:NOC-Senior Regional MMKT Mgr') ||(ur.Name == 'MMKT:EOC-Senior Regional MMKT Mgr'))){
                    if(RegionalBudget.Submit__c){ 
                        msg = '已提交申请，不能再修改！';
                        DisplaySave = false;
                        DisplaySubmit = false;
                        DisplayApprove = false;                  
                    }
               } 
               if((ExistRecord.size() > 0)&&((ur.Name == 'EOC Regional General Manager')|| (ur.Name == 'NOC Regional General Manager') || 
                   (ur.Name == 'SOC Regional General Manager') ||(ur.Name == 'WOC Regional General Manager'))){
                   if(!RegionalBudget.Submit__c){
                        msg = '未提交审批';
                        DisplaySubmit = false;
                        DisplaySave = false;
                        DisplayApprove = false; 
                       
                   }
               } 
           }                
       }
        if(((ur.Name == 'WOC Regional General Manager')||(ur.Name == 'SOC Regional General Manager')||
        (ur.Name == 'NOC Regional General Manager')||(ur.Name == 'EOC Regional General Manager'))&&(DisplaySave == false))
        {
            PESM  = null; 
        }     
     
    }

    public void SetRecord(Boolean Submit)
    {
        // update or insert the records
        List<Sub_regional_Monthly_Budget__c> SubRegionMonBudgetList = new List<Sub_regional_Monthly_Budget__c>();
        for(TableItemControl t : TableItemsDown){
            if(T.Str == '总计')
            {
                continue;
            }

            t.SRMB.Name = PESM.Year__c + '年' + IdSelect + t.str + '月专业样品管理';
            t.SRMB.Month__c = t.str;
            t.SRMB.Budget_RMB__c = t.SRMB.Budget_KG__c * ExistRecord[0].Rate__c;
            if(t.SRMB.Budget_KG__c > 0)
                t.SRMB.This_year_In_market_sales_kg__c = t.SRMB.InMarketValueHide__c / t.SRMB.Budget_KG__c;
            else
                t.SRMB.This_year_In_market_sales_kg__c = 0;
            t.SRMB.This_year_In_market_sales_kg__c = t.SRMB.This_year_In_market_sales_kg__c.intValue();
            if(t.SRMB.ConversionForcast__c > 0)
                t.SRMB.This_year_PE_Sample_kg__c = t.SRMB.Budget_KG__c / t.SRMB.ConversionForcast__c;
            else
                t.SRMB.This_year_PE_Sample_kg__c = 0;
            t.SRMB.This_year_PE_Sample_kg__c = t.SRMB.This_year_PE_Sample_kg__c.intValue();            
            if(!ForUpdate){
                t.SRMB.Sub_Region_Budget__c = SelectedRecord.id;
            }
                
            SubRegionMonBudgetList.add(t.SRMB);
        }
        if((IdSelect != '1') && (IdSelect != ' '))
        {
            if(ForUpdate)
                update SubRegionMonBudgetList;
            else{
                insert SubRegionMonBudgetList;
                ForUpdate = true;
            }         
        }
   
        msg = null;   
    }


    public void Save()
    {
        if(!PESM.Deal__c)
        {
            return;
        }
        Decimal AllocatedNum = decimal.valueof(0);     
        
        for(TableItemControl t : TableItemsDown){
            if(T.Str == '总计')
            {
                continue;
            }
            if((t.SRMB.Budget_KG__c != null)&&(t.SRMB.Budget_KG__c > 0)){
                if((AllocatedNum == null)||(AllocatedNum == 0))
                    AllocatedNum = t.SRMB.Budget_KG__c;
                else
                    AllocatedNum += t.SRMB.Budget_KG__c;
            }    
        }
      
        if(AllocatedNum != SelectedRecord.Total_budget_kg__c)
        {
            msg = '分配公斤数应等于分配到片区的预算公斤数';
            return;
        }  

        if((ur.Name == 'WOC Regional General Manager')||(ur.Name == 'SOC Regional General Manager')||
            (ur.Name == 'NOC Regional General Manager')||(ur.Name == 'EOC Regional General Manager'))
        {
            SetRecord(true);
        }
        else
            SetRecord(false); 
        
        ExistRecord = [Select s.total_score__c, s.potential_score__c, s.final_weighting__c, s.Year__c, s.Total_budget_kg__c,
            s.Total_budget_RMB__c, s.This_year_PE_Sample_kg__c, s.This_year_In_market_sales_kg__c,  s.Submit__c, s.Sub_Region__c, s.Sales_City__c, s.Region__c, 
            s.Rate__c, s.Place__c, s.PE_Sample_Management__c, s.OwnerId, s.Name, s.Line_Manager__c, s.Last_year_sales_weighting__c,
            s.Last_year_conversion_weighting__c, s.Last_year_PE_Sample_kg__c, s.Last_year_In_market_sales_kg__c, s.IsDeleted, s.Id, s.Area__c, s.Approved__c,s.Changed__c 
            ,s.RegionalBudget__c From Sub_Region_Budget__c s Where s.RegionalBudget__c =: RegionalId];    
    }

    public PageReference Submit()
    {
    
        List<Sub_Region_Budget__c> SubmitSRBL = new List<Sub_Region_Budget__c>();
        List<Sub_Region_Budget__Share> InsertRGMShare = new List<Sub_Region_Budget__Share>();
        User RGMuser = new User();    
        
        if(pList[0].Region__r.name == '华南区')
        {
            RGMuser = [Select id From User Where UserRoleId =: RoleSOCRGM.id limit 1];
        }
        else if(pList[0].Region__r.name == '华东区')
        {
            RGMuser = [Select id From User Where UserRoleId =: RoleEOCRGM.id limit 1];
        }
        
        else if(pList[0].Region__r.name == '华北区')
        {
            RGMuser = [Select id From User Where UserRoleId =: RoleNOCRGM.id limit 1];
        }
        else
        {
            RGMuser = [Select id From User Where UserRoleId =: RoleWOCRGM.id limit 1];
        }
        
        for(Place__c p : pList) 
        {
           List<Sub_Region_Budget__c>  SubmitSRB = [Select s.total_score__c, s.potential_score__c, s.RGM__r.email,
                s.final_weighting__c, s.Year__c, s.Total_budget_kg__c, s.Total_budget_RMB__c, s.This_year_PE_Sample_kg__c, 
                s.This_year_In_market_sales_kg__c,  s.Submit__c, s.Sub_Region__c, s.Sales_City__c, s.Region__c, 
                s.Rate__c, s.Place__c, s.PE_Sample_Management__c, s.OwnerId, s.Name, s.Line_Manager__c, s.Last_year_sales_weighting__c,
                s.Last_year_conversion_weighting__c, s.Last_year_PE_Sample_kg__c, s.Last_year_In_market_sales_kg__c, s.IsDeleted, s.Id, s.Area__c, s.Approved__c,s.Changed__c 
                From Sub_Region_Budget__c s Where s.name =: PESM.Year__c +'年' + p.Name + '专业样品管理' and s.PE_Sample_Management__c =: PESM.Id];          
            if(SubmitSRB.size() > 0)
            {
                SubmitSRBL.add(SubmitSRB[0]);
            
                Sub_Region_Budget__Share mShare = new Sub_Region_Budget__Share();
                mShare.ParentId = SubmitSRB[0].id;
                mShare.UserOrGroupId = RGMuser.id;
                mShare.AccessLevel = 'Edit';
                InsertRGMShare.add(mShare); 
             }             
        }
        insert InsertRGMShare;
        
        for(Sub_Region_Budget__c s : SubmitSRBL)
        {
            if(s.Changed__c == Inequality)
            {
                msg = s.name + '预算没分配完成';
                return null;
            }
        }
        String emailAddresses;   
        for(Sub_Region_Budget__c  s : SubmitSRBL)
        {
            //s.Submit__c = true;
            //s.ApprovalStatus__c = '等待大区经理审批';
            emailAddresses = s.RGM__r.email;
        }
        update SubmitSRBL;
        
        RegionalBudget.ApprovalStatus__c = '等待大区经理审批';
        RegionalBudget.Submit__c = true;
        update RegionalBudget;
        
        
        if(emailAddresses != null){
            List<String> toAddresses = new List<String>();  
            toAddresses.add( emailAddresses );  
            List<String> ccAddresses = new List<String>();
            String Body = '您好！\n' + '您收到一个' + '您收到一个新的' + pList[0].Region__r.name + '专业样品管理申请!\n' + string.valueof(Date.Today());
            String Subject = pList[0].Region__r.name + '申请';
                  
            EmailFunction.SendEmail(toAddresses, ccAddresses, Body, Subject);
        }


    
        pageReference pr = new pageReference('/'+ RegionalId);     
        pr.setredirect(true);      
        return pr;
    }
            
    public PageReference Cancel()
    {
        pageReference pr = new pageReference('/'+ RegionalId);     
        pr.setredirect(true);      
        return pr;
    }

    public PageReference Approve()
    {        
        List<Sub_Region_Budget__c> SubmitSRBL = new List<Sub_Region_Budget__c>();
        for(Sub_Region_Budget__c s : ExistRecord)
        {
            if(s.Changed__c == Inequality)
            {
                msg = s.name + '预算没分配完成';
                return null;
            }
        }

        for(Place__c p : pList) 
        {
           List<Sub_Region_Budget__c>  SubmitSRB = [Select s.total_score__c, s.potential_score__c, 
                s.final_weighting__c, s.Year__c, s.Total_budget_kg__c, s.Total_budget_RMB__c, s.This_year_PE_Sample_kg__c, 
                s.This_year_In_market_sales_kg__c,  s.Submit__c, s.Sub_Region__c, s.Sales_City__c, s.Region__c, 
                s.Rate__c, s.Place__c, s.PE_Sample_Management__c, s.OwnerId, s.Name, s.Line_Manager__c, s.Last_year_sales_weighting__c,
                s.Last_year_conversion_weighting__c, s.Last_year_PE_Sample_kg__c, s.Last_year_In_market_sales_kg__c, s.IsDeleted, s.Id, s.Area__c,s.Changed__c ,
                s.Approved__c From Sub_Region_Budget__c s Where s.name =: PESM.Year__c +'年' + p.Name + '专业样品管理' and s.PE_Sample_Management__c =: PESM.Id];          
            
            if(SubmitSRB.size() > 0)
                SubmitSRBL.add(SubmitSRB[0]);
        }
        
        RegionalBudget.ApprovalStatus__c = '等待全国医务市场总监审批';
        RegionalBudget.Approved__c = true;
        update RegionalBudget;
        
        // trigger regional approval
   
        Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();   
        req1.setObjectId(RegionalId);
        Approval.ProcessResult result = Approval.process(req1);   

            
        pageReference pr = new pageReference('/'+ RegionalId);     
        pr.setredirect(true);      
        return pr;
    }
    
    static testMethod void OverrideViewTest()
    {
        Profile p  = [select id from profile where name = 'System Administrator'or name =: '系统管理员'];
        UserRole SRMMM_SOC = [Select Id,Name From UserRole Where Name =: GlobalProperties.SRMMM_SOC];
        
        User u1 = new User (alias = 'standt', email = 'shuaicao@isoftstone.com', emailencodingkey='UTF-8', UserRoleId = SRMMM_SOC.id,
                lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', Title__c = 'Sales Rep',profileid = p.id, 
                timezonesidkey = 'America/Los_Angeles', username='asdfdaa@testorg1.com');
        insert u1;
        
        System.runAs(u1) {
            PE_Sample_Management__c PE = new PE_Sample_Management__c();
            PE.WOC_Total_budget_RMB__c = 1;
            PE.Deal__c = true;
            PE.WOC_budget_allocation_kg__c = 2;
            PE.WOCInMarketValueHide__c = 0;
            PE.WOCConversionForcast__c = 0;                  
            PE.SOC_Total_budget_RMB__c = 0;
            PE.SOC_budget_allocation_kg__c = 0;
            PE.SOCInMarketValueHide__c = 0;
            PE.SOCConversionForcast__c = 0;                  
            PE.EOC_Total_budget_RMB__c = 0;
            PE.EOC_budget_allocation_kg__c = 0;
            PE.EOCInMarketValueHide__c = 0;
            PE.EOCConversionForcast__c = 0;            
            PE.NOC_Total_budget_RMB__c = 0;
            PE.NOC_budget_allocation_kg__c = 0;
            PE.NOCInMarketValueHide__c = 0;
            PE.NOCConversionForcast__c = 0;
            PE.Rate__c =2;
            PE.Total_Budget_Allocation_RMB__c = 1;
            insert PE;
            
            RegionalBudget__c RB = new RegionalBudget__c();
            RB.PESampleManagement__c = PE.id;
            insert RB;
            
            Sub_Region_Budget__c SRB = new Sub_Region_Budget__c();
            SRB.PE_Sample_Management__c = PE.id;
            SRB.RegionalBudget__c = RB.id;
            insert SRB;
            
            test.setCurrentPageReference(Page.OverrideSubRegionBudgetNew);
            System.currentPageReference().getParameters().put('id', PE.Id);       
            System.currentPageReference().getParameters().put('Rid', RB.Id);       
            
            OverrideSubRegionMonthlyBudget testCase = new OverrideSubRegionMonthlyBudget();
            testCase.PESM.Deal__c = true;
            system.assert(testCase.options != null);
            testCase.actionSupport();
            testCase.Save();
            testCase.Submit();
            testCase.Cancel();
            testCase.Approve();
            
        
        }           
    }
 
}